/*
 * Copyright 2013-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.gateway.handler.predicate;

import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

import jakarta.validation.constraints.NotNull;

import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author Spencer Gibb
 * <p>
 *     BetweenRoutePredicateFactory 是 Spring Cloud Gateway 中的一个具体实现类，用于定义 "在两个时间点之间" 的路由谓词。它的作用是根据请求的时间戳判断是否满足条件（即当前时间是否在指定的两个时间点之间）。
 *     以下是对其功能、设计和使用场景的详细解析。
 * 1. 核心功能
 * 1.1 路由匹配逻辑
 * BetweenRoutePredicateFactory 的核心逻辑是：
 * 检查当前时间 (ZonedDateTime.now()) 是否在配置的两个时间点之间。
 * 如果满足条件，则返回 true，表示请求匹配该路由；否则返回 false。
 * 1.2 配置支持
 * 它继承了 AbstractRoutePredicateFactory，并实现了快捷配置支持。
 * 通过 shortcutFieldOrder 方法定义了快捷配置的字段顺序，允许用户以简化的形式定义参数。
 * 1.3 自定义谓词
 * 它返回一个自定义的 GatewayPredicate 实现，包含以下内容：
 * 匹配逻辑（test 方法）。
 * 配置对象（getConfig 方法）。
 * 可读性描述（toString 方法）。
 *
 * spring:
 *   cloud:
 *     gateway:
 *       routes:
 *         - id: example_route
 *           uri: http://example.org
 *           predicates:
 *             - Between=2025-04-11T17:11:00+08:00[Asia/Shanghai], 2025-04-11T18:11:00+08:00[Asia/Shanghai]
 * </p>
 */
public class BetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<BetweenRoutePredicateFactory.Config> {

	/**
	 * DateTime 1 key.
	 */
	public static final String DATETIME1_KEY = "datetime1";

	/**
	 * DateTime 2 key.
	 */
	public static final String DATETIME2_KEY = "datetime2";

	public BetweenRoutePredicateFactory() {
		super(Config.class);
	}

	/**
	 * 功能：定义快捷配置的字段顺序。
	 * 场景：
	 * 在快捷配置中，datetime1 和 datetime2 是两个必须的参数。
	 * @return
	 */
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList(DATETIME1_KEY, DATETIME2_KEY);
	}

	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		Assert.isTrue(config.getDatetime1().isBefore(config.getDatetime2()),
				config.getDatetime1() + " must be before " + config.getDatetime2());

		return new GatewayPredicate() {
			@Override
			public boolean test(ServerWebExchange serverWebExchange) {
				final ZonedDateTime now = ZonedDateTime.now();
				return now.isAfter(config.getDatetime1()) && now.isBefore(config.getDatetime2());
			}

			@Override
			public Object getConfig() {
				return config;
			}

			@Override
			public String toString() {
				return String.format("Between: %s and %s", config.getDatetime1(), config.getDatetime2());
			}
		};
	}

	@Validated
	public static class Config {

		@NotNull
		private ZonedDateTime datetime1;

		@NotNull
		private ZonedDateTime datetime2;

		public ZonedDateTime getDatetime1() {
			return datetime1;
		}

		public Config setDatetime1(ZonedDateTime datetime1) {
			this.datetime1 = datetime1;
			return this;
		}

		public ZonedDateTime getDatetime2() {
			return datetime2;
		}

		public Config setDatetime2(ZonedDateTime datetime2) {
			this.datetime2 = datetime2;
			return this;
		}

	}

}
